using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml;

namespace TmxUtil
{
    [Serializable]
    public class Solution
    {
        public string DefaultCultureName;
        public string SlnFile;
        public List<Project> Projects = new List<Project>();


        public Solution(string slnFile)
        {
            SlnFile = slnFile;
        }

        public string[] GetLocalizationCultures()
        {
            List<ResX> allResX = new List<ResX>();
            foreach (Project p in this.Projects)
                allResX.AddRange(p.ResXList);

            List<string> all = new List<string>(new ResXCollection(allResX).GetCultures());
            List<string> ret = new List<string>();
            foreach(string c in all)
                if (c != string.Empty)
                    ret.Add(c);

            ret.Sort();
            return ret.ToArray();
        }

        public string FullName
        {
            get
            {
                return new FileInfo(SlnFile).FullName;
            }
        }

        public string GetRelativePath(string fullName)
        {
            string s = FullName;
            string sd = Path.GetDirectoryName(s);
            if (!sd.EndsWith(Path.DirectorySeparatorChar.ToString()))
                sd += Path.DirectorySeparatorChar;

            string f = new FileInfo(fullName).FullName;
            if (f.ToLower().StartsWith(sd.ToLower()))
            {
                return f.Substring(sd.Length);
            }
            else
                throw new ArgumentException("File " + f + " is outside solution folder [" + sd + "]");
        }

        public static class XmlWriter
        {
            public static void Write(Solution solution, XmlTextWriter writer)
            {
                writer.WriteStartElement("solution");
                foreach(Project p in solution.Projects)
                {
                    string bin =
                        p.Binaries.Latest != null
                            ? solution.GetRelativePath(p.Binaries.Latest.FullName)
                            : null;

                    writer.WriteStartElement("project");
                    if (bin != null)
                        writer.WriteAttributeString("binary", bin);

                    writer.WriteAttributeString("file", p.File);
                    writer.WriteAttributeString("namespace", p.RootNamespace);
                    writer.WriteAttributeString("type", p.OutputType.ToString());
                    writer.WriteEndElement();
                }
                writer.WriteEndElement();
            }
        }
    }
}
